/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.howtimeflies.simplecrypt;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.Random;

/**
 * 第0位记录一个值（1-5）随机一个，例如2
 * 第1-5位为5个值中记录一个随机长度，例如0,20,0,0,0
 * 接着记录20位随机值。
 *
 * 头部总长度是 1+posMax+随机值
 *
 * Created by zhangg on 2015/5/25 0025 17:47.
 *
 * @author <a href=mailto:zhanggeng@howtimeflies.org>GengZhang</a>
 */
public class RandomHeadAlgorithm implements Algorithm {

    private int posMax;
    private int headMax;

    public RandomHeadAlgorithm() {
        posMax = 5;
        headMax = 10;
    }

    @Override
    public String name() {
        return "randomHead";
    }

    @Override
    public int encode(RandomAccessFile file) throws IOException {
        //例如3
        int lenPos = 1 + new Random().nextInt(posMax);
        // 例如12
        int fixLength = 10 + new Random().nextInt(headMax);
        file.seek(0);
        file.writeByte(lenPos); // 第0位
        for (int i = 1; i < 6; i++) {
            file.write(i == lenPos ? fixLength : 0); // 1-6位
        }
        byte[] head = new byte[fixLength];
        Arrays.fill(head, (byte) new Random().nextInt(100));
        file.write(head);
//        System.out.println(lenPos + " " + fixLength);
        return lenPos + fixLength + 1;
    }

    @Override
    public int decode(RandomAccessFile file) throws IOException {
        file.seek(0);
        byte lenPos = file.readByte();
        file.seek(lenPos);
        byte fixLength= file.readByte();
//        System.out.println(lenPos + " " + fixLength);
        file.seek(0);
        return posMax + fixLength + 1;
    }
}
